package cn.mg.framework.response;

import cn.mg.framework.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author hezhaoming
 * @date 2019-11-05
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class PlatformErrorResult implements Result {

    private static final long serialVersionUID = 1899083570489722793L;

    /**
     * 异常堆栈的精简信息
     */
    private String message;

    /**
     * 我们系统内部自定义的返回值编码，{@link ResponseCode} 它是对错误更加详细的编码
     * <p>
     * 备注：spring boot默认返回异常时，该字段为null
     */
    private String code;

    /**
     * 调用接口路径
     */
    private String path;

    /**
     * 异常的名字
     */
    private String exception;

    /**
     * 异常的错误传递的数据
     */
    private Object errors;

    /**
     * 时间戳
     */
    private Date timestamp;


    public static PlatformErrorResult failure(ResponseCode resultCode, Throwable e, Object errors) {
        PlatformErrorResult result = PlatformErrorResult.failure(resultCode, e);
        result.setErrors(errors);
        return result;
    }

    public static PlatformErrorResult failure(ResponseCode resultCode, Throwable e) {
        PlatformErrorResult result = new PlatformErrorResult();
        result.setCode(resultCode.code());
        result.setMessage(resultCode.message());
        result.setException(e.getClass().getName());
        result.setErrors(e.getMessage());
        result.setPath(RequestContextHolderUtil.getRequest().getRequestURI());
        result.setTimestamp(new Date());
        return result;
    }

    public static PlatformErrorResult failure(BusinessException e) {
        return PlatformErrorResult.failure(e.getResultCode(), e, e.getData());
    }
}
